import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Conversation, Message } from '@/types'
import { messageApi } from '@/api'

export const useChatStore = defineStore(
  'chat',
  () => {
    // 状态
    const conversations = ref<Conversation[]>([])
    const currentConversation = ref<number | null>(null)
    const messages = ref<Map<number, Message[]>>(new Map())

    // 计算属性
    const unreadCount = computed(() => {
      return conversations.value.reduce((sum, conv) => sum + conv.unreadCount, 0)
    })

    const currentMessages = computed(() => {
      if (!currentConversation.value) return []
      return messages.value.get(currentConversation.value) || []
    })

    /**
     * 获取会话列表
     */
    const fetchConversations = async (page: number = 1, size: number = 20) => {
      try {
        const res = await messageApi.getConversations({ page, size })
        if (page === 1) {
          conversations.value = res.conversations
        } else {
          conversations.value.push(...res.conversations)
        }
      } catch (err) {
        console.error('获取会话列表失败:', err)
      }
    }

    /**
     * 获取聊天记录
     */
    const fetchMessages = async (
      conversationId: number,
      page: number = 1,
      size: number = 20
    ) => {
      try {
        const res = await messageApi.getMessages(conversationId, { page, size })

        const existingMessages = messages.value.get(conversationId) || []
        if (page === 1) {
          messages.value.set(conversationId, res.messages)
        } else {
          messages.value.set(conversationId, [...res.messages, ...existingMessages])
        }

        return res.hasMore
      } catch (err) {
        console.error('获取聊天记录失败:', err)
        return false
      }
    }

    /**
     * 发送消息
     */
    const sendMessage = async (
      conversationId: number,
      data: {
        contentType: string
        content?: string
        mediaUrl?: string
        locationInfo?: any
      }
    ) => {
      try {
        const res = await messageApi.sendMessage(conversationId, data)

        // 添加消息到本地
        const message: Message = {
          id: res.messageId,
          fromUserId: 0, // 当前用户ID
          toUserId: 0, // 对方用户ID
          contentType: data.contentType as any,
          content: data.content,
          mediaUrl: data.mediaUrl,
          locationInfo: data.locationInfo,
          isRead: false,
          createdAt: res.createdAt
        }

        addMessage(message)

        // 更新会话的最后一条消息
        updateConversationLastMessage(conversationId, message)

        return true
      } catch (err: any) {
        console.error('发送消息失败:', err)
        uni.showToast({
          title: err.message || '发送失败',
          icon: 'none'
        })
        return false
      }
    }

    /**
     * 创建会话
     */
    const createConversation = async (data: {
      targetUserId: number
      postId?: number
      firstMessage?: string
    }) => {
      try {
        const res = await messageApi.createConversation(data)
        return res.conversationId
      } catch (err: any) {
        console.error('创建会话失败:', err)
        uni.showToast({
          title: err.message || '创建会话失败',
          icon: 'none'
        })
        return null
      }
    }

    /**
     * 标记消息已读
     */
    const markRead = async (conversationId: number) => {
      try {
        await messageApi.markRead(conversationId)

        // 更新本地未读数
        const conversation = conversations.value.find(c => c.id === conversationId)
        if (conversation) {
          conversation.unreadCount = 0
        }

        // 更新消息已读状态
        const conversationMessages = messages.value.get(conversationId)
        if (conversationMessages) {
          conversationMessages.forEach(msg => {
            msg.isRead = true
          })
        }
      } catch (err) {
        console.error('标记已读失败:', err)
      }
    }

    /**
     * 添加消息(WebSocket推送或本地发送)
     */
    const addMessage = (message: Message) => {
      const conversationId = currentConversation.value
      if (!conversationId) return

      const conversationMessages = messages.value.get(conversationId) || []
      conversationMessages.push(message)
      messages.value.set(conversationId, conversationMessages)
    }

    /**
     * 更新会话的最后一条消息
     */
    const updateConversationLastMessage = (conversationId: number, message: Message) => {
      const conversation = conversations.value.find(c => c.id === conversationId)
      if (conversation) {
        conversation.lastMessage = {
          content: message.content || '[图片]',
          contentType: message.contentType,
          createdAt: message.createdAt
        }
        conversation.updatedAt = message.createdAt

        // 将会话置顶
        const index = conversations.value.indexOf(conversation)
        if (index > 0) {
          conversations.value.splice(index, 1)
          conversations.value.unshift(conversation)
        }
      }
    }

    /**
     * 设置当前会话
     */
    const setCurrentConversation = (conversationId: number | null) => {
      currentConversation.value = conversationId
    }

    /**
     * 清空聊天记录
     */
    const clearMessages = (conversationId: number) => {
      messages.value.delete(conversationId)
    }

    return {
      conversations,
      currentConversation,
      messages,
      unreadCount,
      currentMessages,
      fetchConversations,
      fetchMessages,
      sendMessage,
      createConversation,
      markRead,
      addMessage,
      updateConversationLastMessage,
      setCurrentConversation,
      clearMessages
    }
  }
)
